package org.andromeo.connectionapi;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.andromeo.ARException;
import org.andromeo.GRSession;
import org.andromeo.util.ARRequester;

public class HeartbeatProcessor {

	// notify patterns: are there any new informations?
	private static final Pattern msgNotePattern = Pattern
			.compile("\"msgNote\":(\\d)+");
	private static final Pattern favNotePattern = Pattern
			.compile("\"favNote\":(\\d)+");
	private static final Pattern visNotePattern = Pattern
			.compile("\"visNote\":(\\d)+");

	// counter patterns: how many new messages are available?
	private static final Pattern msgCountPattern = Pattern
			.compile("\"msgCount\":\"(\\d)+\"");

	private static final Pattern checkLoggedOutPattern = Pattern.compile(
			"alert\\(\".*?logged\\sout.*?\"",
			Pattern.DOTALL);

	/**
	 * sends a heartbeat and checks if any notes were set.
	 * 
	 * @param grsession
	 * @return true if a refresh of other/all information is needed, false if
	 *         not
	 * @throws ARException
	 * @throws IOException
	 */
	public static boolean sendHearbeat(GRSession grsession) throws ARException,
			IOException {

		boolean gayromeoRequestsFullRefresh = false;

		String response = null;

		String urlpath = grsession.getGrurl();
		urlpath += grsession.getPhpSessionID();
		urlpath += "/main/heartbeat.php";

		response = ARRequester.sendRequest(grsession, urlpath, "");

		String msgNoteString = "0";
		String favNoteString = "0";
		String visNoteString = "0";

		Matcher msgNoteMatcher = msgNotePattern.matcher(response);
		Matcher favNoteMatcher = favNotePattern.matcher(response);
		Matcher visNoteMatcher = visNotePattern.matcher(response);
		Matcher msgCountMatcher = msgCountPattern.matcher(response);
		Matcher checkLoggedOutMatcher = checkLoggedOutPattern.matcher(response);

		// check if we've been logged out already
		if (checkLoggedOutMatcher.find()) {
			grsession.setSessionStatus(GRSession.STATUS_ERR_TIMEOUT);
			throw new ARException(ARException.AREXC_SESSION_TIMEOUT);
		}

		if (msgNoteMatcher.find())
			msgNoteString = msgNoteMatcher.group(1);
		if (favNoteMatcher.find())
			favNoteString = favNoteMatcher.group(1);
		if (visNoteMatcher.find())
			visNoteString = visNoteMatcher.group(1);

		if (!msgNoteString.equals("0"))
			gayromeoRequestsFullRefresh = true;
		else if (!favNoteString.equals("0"))
			gayromeoRequestsFullRefresh = true;
		else if (!visNoteString.equals("0"))
			gayromeoRequestsFullRefresh = true;
		else if (msgCountMatcher.find()) {
			int i = Integer.parseInt(msgCountMatcher.group(1));
			if (i != grsession.getMessageFactory().getNewMsgList().size())
				gayromeoRequestsFullRefresh = true;
		}

		return gayromeoRequestsFullRefresh;
	}

}
